"""
API路由模块
提供RESTful API接口
"""
from flask import Blueprint, request, jsonify
from flask_login import current_user
from flask_jwt_extended import jwt_required, get_jwt_identity

from app import db
from app.models.user import User
from app.models.forum import Post, Comment, Category
from app.models.chat import ChatRoom, Message
from app.auth.decorators import handle_exceptions, permission_required, validate_schema
from app.utils.helpers import format_timestamp, sanitize_html

api_bp = Blueprint('api', __name__, url_prefix='/api')

@api_bp.route('/')
def api_index():
    """
    API首页 - 显示API信息
    """
    return jsonify({
        'name': 'SteHub API',
        'version': '2.0.0',
        'description': 'SteHub 学生交流平台 RESTful API',
        'endpoints': {
            'auth': {
                'login': '/api/auth/login',
                'register': '/api/auth/register',
                'refresh': '/api/auth/refresh',
                'profile': '/api/auth/profile'
            },
            'forum': {
                'posts': '/api/forum/posts',
                'post_detail': '/api/forum/posts/<id>',
                'categories': '/api/forum/categories'
            },
            'chat': {
                'rooms': '/api/chat/rooms',
                'messages': '/api/chat/rooms/<id>/messages'
            },
            'users': {
                'profile': '/api/users/<id>',
                'online': '/api/users/online'
            }
        }
    })

# 认证相关API
@api_bp.route('/auth/login', methods=['POST'])
@handle_exceptions
def api_login():
    """
    API登录
    """
    from app.routes.auth import get_token
    return get_token()

@api_bp.route('/auth/register', methods=['POST'])
@handle_exceptions
def api_register():
    """
    API注册
    """
    data = request.get_json()
    
    if not data:
        return jsonify({
            'error': '请求数据必须是JSON格式',
            'code': 'INVALID_JSON'
        }), 400
    
    # 验证必填字段
    required_fields = ['username', 'email', 'password']
    for field in required_fields:
        if not data.get(field):
            return jsonify({
                'error': f'缺少必填字段: {field}',
                'code': 'MISSING_FIELD'
            }), 400
    
    # 验证用户名和邮箱格式
    from app.utils.helpers import validate_username, validate_email
    if not validate_username(data['username']):
        return jsonify({
            'error': '用户名格式不正确',
            'code': 'INVALID_USERNAME'
        }), 400
    
    if not validate_email(data['email']):
        return jsonify({
            'error': '邮箱格式不正确',
            'code': 'INVALID_EMAIL'
        }), 400
    
    # 验证密码强度
    from app.auth.utils import validate_password_strength
    is_valid, message = validate_password_strength(data['password'])
    if not is_valid:
        return jsonify({
            'error': message,
            'code': 'WEAK_PASSWORD'
        }), 400
    
    # 检查用户名和邮箱是否已存在
    if User.query.filter_by(username=data['username']).first():
        return jsonify({
            'error': '该用户名已被使用',
            'code': 'USERNAME_EXISTS'
        }), 400
    
    if User.query.filter_by(email=data['email']).first():
        return jsonify({
            'error': '该邮箱已被注册',
            'code': 'EMAIL_EXISTS'
        }), 400
    
    try:
        # 创建用户
        user = User(
            username=data['username'],
            email=data['email']
        )
        user.set_password(data['password'])
        
        db.session.add(user)
        db.session.commit()
        
        # 生成JWT令牌
        from app.auth.utils import generate_jwt_tokens
        tokens = generate_jwt_tokens(user)
        
        return jsonify({
            'success': True,
            'message': '注册成功',
            'user': {
                'id': user.id,
                'username': user.username,
                'email': user.email
            },
            'tokens': tokens
        }), 201
    
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'error': '注册失败',
            'code': 'REGISTRATION_FAILED'
        }), 500

@api_bp.route('/auth/refresh', methods=['POST'])
@handle_exceptions
def api_refresh_token():
    """
    API刷新令牌
    """
    from app.routes.auth import refresh_token
    return refresh_token()

@api_bp.route('/auth/profile', methods=['GET', 'PUT'])
@jwt_required()
@handle_exceptions
def api_profile():
    """
    API获取或更新用户资料
    """
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)
    
    if request.method == 'GET':
        return jsonify({
            'success': True,
            'user': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'bio': user.bio,
                'avatar_url': user.avatar_url,
                'role': user.role,
                'is_online': user.is_online,
                'created_at': format_timestamp(user.created_at),
                'last_seen': format_timestamp(user.last_seen)
            }
        })
    
    # PUT请求更新资料
    data = request.get_json()
    
    if not data:
        return jsonify({
            'error': '请求数据必须是JSON格式',
            'code': 'INVALID_JSON'
        }), 400
    
    try:
        updated = False
        
        # 更新用户名
        if 'username' in data and data['username'] != user.username:
            from app.utils.helpers import validate_username
            if not validate_username(data['username']):
                return jsonify({
                    'error': '用户名格式不正确',
                    'code': 'INVALID_USERNAME'
                }), 400
            
            if User.query.filter_by(username=data['username']).first():
                return jsonify({
                    'error': '该用户名已被使用',
                    'code': 'USERNAME_EXISTS'
                }), 400
            
            user.username = data['username']
            updated = True
        
        # 更新邮箱
        if 'email' in data and data['email'] != user.email:
            from app.utils.helpers import validate_email
            if not validate_email(data['email']):
                return jsonify({
                    'error': '邮箱格式不正确',
                    'code': 'INVALID_EMAIL'
                }), 400
            
            if User.query.filter_by(email=data['email']).first():
                return jsonify({
                    'error': '该邮箱已被使用',
                    'code': 'EMAIL_EXISTS'
                }), 400
            
            user.email = data['email']
            updated = True
        
        # 更新其他字段
        if 'bio' in data:
            user.bio = data['bio'][:500]  # 限制长度
            updated = True
        
        if 'avatar_url' in data:
            user.avatar_url = data['avatar_url']
            updated = True
        
        if updated:
            db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '资料更新成功',
            'user': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'bio': user.bio,
                'avatar_url': user.avatar_url
            }
        })
    
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'error': '资料更新失败',
            'code': 'UPDATE_FAILED'
        }), 500

# 论坛相关API
@api_bp.route('/forum/posts')
def api_forum_posts():
    """
    API获取帖子列表
    """
    from app.routes.forum import api_posts
    return api_posts()

@api_bp.route('/forum/posts/<int:post_id>')
def api_forum_post_detail(post_id):
    """
    API获取帖子详情
    """
    from app.routes.forum import api_post_detail
    return api_post_detail(post_id)

@api_bp.route('/forum/posts', methods=['POST'])
@jwt_required()
@handle_exceptions
def api_create_post():
    """
    API创建帖子
    """
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)
    
    data = request.get_json()
    
    if not data:
        return jsonify({
            'error': '请求数据必须是JSON格式',
            'code': 'INVALID_JSON'
        }), 400
    
    # 验证必填字段
    required_fields = ['title', 'content', 'category_id']
    for field in required_fields:
        if not data.get(field):
            return jsonify({
                'error': f'缺少必填字段: {field}',
                'code': 'MISSING_FIELD'
            }), 400
    
    # 验证标题长度
    if len(data['title']) > 200:
        return jsonify({
            'error': '标题长度不能超过200个字符',
            'code': 'TITLE_TOO_LONG'
        }), 400
    
    # 检查分类是否存在
    category = Category.query.get(data['category_id'])
    if not category or not category.is_active:
        return jsonify({
            'error': '选择的分类不存在',
            'code': 'CATEGORY_NOT_FOUND'
        }), 400
    
    try:
        # 创建帖子
        post = Post(
            title=data['title'],
            content=sanitize_html(data['content']),
            author_id=user.id,
            category_id=data['category_id']
        )
        
        db.session.add(post)
        db.session.commit()
        
        # 更新分类帖子计数
        category.post_count += 1
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '帖子创建成功',
            'post': {
                'id': post.id,
                'title': post.title,
                'content': post.content,
                'author': {
                    'id': user.id,
                    'username': user.username
                },
                'category': {
                    'id': category.id,
                    'name': category.name
                },
                'created_at': format_timestamp(post.created_at)
            }
        }), 201
    
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'error': '帖子创建失败',
            'code': 'POST_CREATION_FAILED'
        }), 500

@api_bp.route('/forum/posts/<int:post_id>/comments', methods=['POST'])
@jwt_required()
@handle_exceptions
def api_create_comment(post_id):
    """
    API创建评论
    """
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)
    
    post = Post.query.get_or_404(post_id)
    
    if not post.is_published:
        return jsonify({
            'error': '帖子不存在或无权评论',
            'code': 'POST_NOT_FOUND'
        }), 404
    
    data = request.get_json()
    
    if not data or not data.get('content'):
        return jsonify({
            'error': '评论内容不能为空',
            'code': 'MISSING_CONTENT'
        }), 400
    
    if len(data['content']) > 1000:
        return jsonify({
            'error': '评论内容不能超过1000个字符',
            'code': 'CONTENT_TOO_LONG'
        }), 400
    
    try:
        # 创建评论
        comment = Comment(
            content=sanitize_html(data['content']),
            author_id=user.id,
            post_id=post_id,
            parent_id=data.get('parent_id')
        )
        
        db.session.add(comment)
        
        # 更新帖子评论计数
        post.comment_count += 1
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '评论发布成功',
            'comment': {
                'id': comment.id,
                'content': comment.content,
                'author': {
                    'id': user.id,
                    'username': user.username,
                    'avatar_url': user.avatar_url
                },
                'post_id': post_id,
                'parent_id': comment.parent_id,
                'created_at': format_timestamp(comment.created_at)
            }
        }), 201
    
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'error': '评论发布失败',
            'code': 'COMMENT_CREATION_FAILED'
        }), 500

# 聊天相关API
@api_bp.route('/chat/rooms')
@jwt_required()
def api_chat_rooms():
    """
    API获取聊天室列表
    """
    from app.routes.chat import api_rooms
    return api_rooms()

@api_bp.route('/chat/rooms/<int:room_id>/messages')
@jwt_required()
def api_chat_room_messages(room_id):
    """
    API获取聊天室消息
    """
    from app.routes.chat import api_room_messages
    return api_room_messages(room_id)

# 用户相关API
@api_bp.route('/users/<int:user_id>')
@handle_exceptions
def api_user_profile(user_id):
    """
    API获取用户资料
    """
    user = User.query.get_or_404(user_id)
    
    if not user.is_active:
        return jsonify({
            'error': '用户不存在',
            'code': 'USER_NOT_FOUND'
        }), 404
    
    return jsonify({
        'success': True,
        'user': {
            'id': user.id,
            'username': user.username,
            'bio': user.bio,
            'avatar_url': user.avatar_url,
            'role': user.role,
            'is_online': user.is_online,
            'created_at': format_timestamp(user.created_at),
            'last_seen': format_timestamp(user.last_seen)
        }
    })

@api_bp.route('/users/online')
def api_online_users():
    """
    API获取在线用户列表
    """
    online_users = User.query.filter_by(is_online=True)\
        .order_by(User.last_seen.desc())\
        .limit(50)\
        .all()
    
    users_data = []
    for user in online_users:
        users_data.append({
            'id': user.id,
            'username': user.username,
            'avatar_url': user.avatar_url,
            'last_seen': format_timestamp(user.last_seen)
        })
    
    return jsonify({
        'success': True,
        'online_users': users_data,
        'count': len(users_data)
    })

# 文件上传API
@api_bp.route('/upload', methods=['POST'])
@jwt_required()
@handle_exceptions
def api_upload_file():
    """
    API文件上传
    """
    from app.storage.manager import storage_manager
    from app.storage.base import StorageType
    
    if 'file' not in request.files:
        return jsonify({
            'error': '没有选择文件',
            'code': 'NO_FILE'
        }), 400
    
    file = request.files['file']
    
    if file.filename == '':
        return jsonify({
            'error': '没有选择文件',
            'code': 'NO_FILE'
        }), 400
    
    try:
        # 获取上传参数
        folder = request.form.get('folder', '')
        metadata = {}
        
        # 保存文件
        result = storage_manager.save(
            file, 
            file.filename, 
            folder=folder, 
            metadata=metadata
        )
        
        return jsonify({
            'success': True,
            'message': '文件上传成功',
            'file': result
        })
    
    except Exception as e:
        return jsonify({
            'error': f'文件上传失败: {str(e)}',
            'code': 'UPLOAD_FAILED'
        }), 500

# 系统状态API
@api_bp.route('/status')
def api_status():
    """
    API系统状态
    """
    from app.routes.main import health_check
    return health_check()

@api_bp.route('/stats')
def api_stats():
    """
    API系统统计
    """
    from app.routes.main import metrics
    return metrics()